package com.css.zfzx.sjcj.modules.yhlevel.repository.impl;

import com.css.zfzx.sjcj.modules.yhlevel.repository.YhDisasterHiddenLevelNativeRepository;
import com.css.zfzx.sjcj.modules.yhlevel.repository.entity.YhDisasterHiddenLevelEntity;
import com.css.zfzx.sjcj.modules.yhlevel.viewobjects.YhDisasterHiddenLevelQueryParams;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
 * @author andy
 * @date 2021-02-03
 */
@Repository
public class YhDisasterHiddenLevelNativeRepositoryImpl implements YhDisasterHiddenLevelNativeRepository {
    @PersistenceContext
    private EntityManager em;

    private static final Logger log = LoggerFactory.getLogger(YhDisasterHiddenLevelNativeRepositoryImpl.class);


    @Override
    public Page<YhDisasterHiddenLevelEntity> queryYhDisasterHiddenLevels(YhDisasterHiddenLevelQueryParams queryParams, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from yh_disaster_hidden_level ");
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if(!PlatformObjectUtils.isEmpty(queryParams.getAddress())) {
            whereSql.append(" and address = :address");
        }
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), YhDisasterHiddenLevelEntity.class);
        StringBuilder countSql = new StringBuilder("select count(*) from yh_disaster_hidden_level ");
        Query countQuery = this.em.createNativeQuery(countSql.append(whereSql).toString());
        if(!PlatformObjectUtils.isEmpty(queryParams.getAddress())) {
            query.setParameter("address", queryParams.getAddress());
            countQuery.setParameter("address", queryParams.getAddress());
        }
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<YhDisasterHiddenLevelEntity> list = query.getResultList();
        BigInteger count = (BigInteger) countQuery.getSingleResult();
        Page<YhDisasterHiddenLevelEntity> yhDisasterHiddenLevelPage = new PageImpl<>(list, pageable, count.longValue());
        return yhDisasterHiddenLevelPage;
    }
}
